package org.springblade.modules.digitalization.utils;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.ofdrw.converter.ofdconverter.ImageConverter;
import org.ofdrw.core.action.Actions;
import org.ofdrw.core.action.CT_Action;
import org.ofdrw.core.action.EventType;
import org.ofdrw.core.action.actionType.actionGoto.CT_Dest;
import org.ofdrw.core.action.actionType.actionGoto.DestType;
import org.ofdrw.core.action.actionType.actionGoto.Goto;
import org.ofdrw.core.basicStructure.doc.Document;
import org.ofdrw.core.basicStructure.doc.permission.CT_Permission;
import org.ofdrw.core.basicStructure.outlines.CT_OutlineElem;
import org.ofdrw.core.basicStructure.outlines.Outlines;
import org.ofdrw.core.basicStructure.pageTree.Pages;
import org.ofdrw.core.basicType.ST_ID;
import org.ofdrw.core.basicType.ST_RefID;
import org.ofdrw.layout.OFDDoc;
import org.ofdrw.layout.PageLayout;
import org.ofdrw.layout.element.Img;
import org.ofdrw.layout.element.Position;
import org.ofdrw.reader.OFDReader;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.modules.digitalization.vo.CatalogItem;
import org.springblade.modules.digitalization.wrapper.UserDaRs;
import org.springblade.modules.digitalization.wrapper.UserMenuRs;

import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class OfdUtils {
	public static final String IMG_ORG = "/图像数据/原始图像数据/";
	public static final String IMG_HD = "/图像数据/优化图像数据/";

	/**
	 * 矫正图片以及返回比例位置
	 *
	 * @param pageLayout
	 * @return
	 */
	private static Double imgWidthAndHighAdapt(Double width, Double height, PageLayout pageLayout) {
		final Double pageLayoutHeight = pageLayout.getHeight();
		final Double pageLayoutWidth = pageLayout.getWidth();
		Double a = pageLayoutHeight / height;
		Double b = pageLayoutWidth / width;
		Double c = Math.min(a, b);
		return c;
	}

	public static Img getImageBylayout(Path filePath, PageLayout pageLayout) throws IOException {
		Img img1 = new Img(pageLayout.getWidth(), pageLayout.getHeight(), filePath);
		final Double aDouble = imgWidthAndHighAdapt(img1.getWidth(), img1.getHeight(), pageLayout);
		img1.setHeight(img1.getHeight() * aDouble);
		img1.setWidth(img1.getWidth() * aDouble);
		img1.setPosition(Position.Static);
		img1.setX(0D).setY(0D);
		img1.setBorderLeft(0D);
		img1.setPaddingLeft(0D)
			.setLeft(0D).setMarginLeft(0D);
		return img1;
	}

	public static void creaateOfdByImgs(String userDataPath, String dirName, UserDaRs userDaRs) {
		String fine = userDaRs.getUserInfo().getUserName() + userDaRs.getUserInfo().getIdCard();
		String format = String.format("%s/%s.ofd", userDataPath, fine);
		try (ImageConverter converter = new ImageConverter(Paths.get(format))) {
			List<UserMenuRs> menus = userDaRs.getMenus();
			for (UserMenuRs menu : menus) {
				log.info("convert document: {}", menu.getClassNum());
				List<String> hdImgs = menu.getHdImgs();
				for (int i = 0; i < hdImgs.size(); i++) {
					String hdImg = hdImgs.get(i);
					log.info("convert document hd image: {} ", hdImg);
					String path = userDataPath + dirName + hdImg;
					try {
						converter.convert(Paths.get(path));
					} catch (Exception e) {
						String message = String.format("OFD文件写入【%s-%s-p%s-%s】错误：%s，下载地址：%s", menu.getClassNum(), menu.getIdNum(), i + 1,
							menu.getCaiLiaoName(), e.getMessage(), path);
						throw new RuntimeException(message);
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
	}

	public static Boolean createOfdByIms(String userD, UserDaRs userDaRs) {
		String fine = userDaRs.getUserInfo().getUserName() + userDaRs.getUserInfo().getIdCard();
		String format = String.format("%s/%s.ofd", userD, fine);
		Path ofdPath = Paths.get(format);
		try (OFDDoc ofdDoc = new OFDDoc(ofdPath)) {
			PageLayout pageLayout = ofdDoc.getPageLayout();
			pageLayout.setMargin(0D, 0D, 0D, 0D);
			ofdDoc.setDefaultPageLayout(pageLayout);

			List<UserMenuRs> menus = userDaRs.getMenus();
			for (UserMenuRs menu : menus) {
				List<String> hdImgs = menu.getHdImgs();
				for (String hdImg : hdImgs) {
					Path path2 = Paths.get(userD + IMG_HD + hdImg);
					Img img1 = new Img(pageLayout.getWidth(), pageLayout.getHeight(), path2);
					final Double aDouble = imgWidthAndHighAdapt(img1.getWidth(), img1.getHeight(), pageLayout);
					img1.setHeight(img1.getHeight() * aDouble);
					img1.setWidth(img1.getWidth() * aDouble);
					img1.setPosition(Position.Static);
					img1.setX(0D).setY(0D);
					img1.setBorderLeft(0D);
					img1.setPaddingLeft(0D)
						.setLeft(0D).setMarginLeft(0D);
					ofdDoc.add(img1);
				}
			}
		} catch (IOException e) {
			System.out.println(e.getStackTrace());
			return false;
		}
		return true;
	}

	public static void createMenu(String ofdPathStr, UserDaRs userDaRs, List<CatalogItem> menus) {
		String fine = userDaRs.getUserInfo().getUserName() + userDaRs.getUserInfo().getIdCard();
		ofdPathStr = String.format("%s/%s.ofd", ofdPathStr, fine);
		Path ofdPath = Paths.get(ofdPathStr);
		try (OFDReader reader = new OFDReader(ofdPath); OFDDoc ofdDoc1 = new OFDDoc(reader, ofdPath)) {
			Pages pages = ofdDoc1.getOfdDocument().getPages();
			List<org.ofdrw.core.basicStructure.pageTree.Page> pages1 = pages.getPages();
			List<ST_ID> collect = pages1.stream().map(p -> p.getID()).collect(Collectors.toList());
			//添加大纲
			addOut(ofdDoc1, collect, menus);
		} catch (IOException e) {
			throw new ServiceException("目录生成失败：" + e.getMessage());
		}
	}

	/**
	 * 添加大纲信息
	 *
	 * @param ofdDoc  文档
	 * @param collect 目录id索引
	 * @param qzMenus 目录详情
	 */


	private static void addOut(OFDDoc ofdDoc, List<ST_ID> collect, List<CatalogItem> qzMenus) {
		Document ofdDocument = ofdDoc.getOfdDocument();
		CT_Permission ct_permission = new CT_Permission();
		ct_permission.setEdit(true);
		ofdDocument.setPermissions(ct_permission);
		Outlines outlines = new Outlines();
		LevPageObj levPageObj = new LevPageObj();
		for (int i = 0; i < qzMenus.size(); i++) {
			outlines.addOutlineElem(getCTOutLineElemByQzMenu(qzMenus.get(i), collect, levPageObj));
		}
		ofdDoc.getOfdDocument().setOutlines(outlines);
		System.out.printf(String.valueOf(ofdDocument));
	}

	/**
	 * 根据目录生成对应的大纲
	 *
	 * @param qzMenu
	 * @return
	 */
	private static CT_OutlineElem getCTOutLineElemByQzMenu(CatalogItem qzMenu, List<ST_ID> collect, LevPageObj levPageObj) {
		CT_OutlineElem ct_outlineElem = new CT_OutlineElem();
		ct_outlineElem.setTitle(qzMenu.getClassNo() + "、" + qzMenu.getRsdaml004());
		if (levPageObj.getLevel() == 0) {
			//当是根目录的话 就是单纯的类号+材料名称
			ct_outlineElem.setTitle(qzMenu.getClassNo() + " " + qzMenu.getRsdaml004());
		} else {
			//递归调用时候，进到二级目录的时候 就是类号+序号+材料名称
			String s = chineseNumberToArabic(qzMenu.getClassNo()) + "-" + (qzMenu.getRsdaml003() == null ? qzMenu.getRsdaml004() :
				qzMenu.getRsdaml003() + " " + qzMenu.getRsdaml004());
			ct_outlineElem.setTitle(chineseNumberToArabic(s));
		}
		if (qzMenu.getRsdaml000() != null) {
			clickAction(ct_outlineElem, collect.get(levPageObj.getPageNum()));
			levPageObj.setPageNum(levPageObj.getPageNum() + qzMenu.getRsdaml005());
		} else {
			clickAction(ct_outlineElem, collect.get(levPageObj.getPageNum()));
		}

		for (CatalogItem qzMenu1 : qzMenu.getChildren()) {
			levPageObj.setLevel(levPageObj.getLevel() + 1);
			CT_OutlineElem ctOutLineElemByQzMenu = getCTOutLineElemByQzMenu(qzMenu1, collect, levPageObj);
			levPageObj.setLevel(levPageObj.getLevel() - 1);
			ct_outlineElem.addOutlineElem(ctOutLineElemByQzMenu);
		}
		return ct_outlineElem;
	}

	public static String chineseNumberToArabic(String s) {
		// Define a mapping of Chinese number characters to Arabic numerals
		String[] chineseDigits = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
		int[] arabicDigits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

		// Replace Chinese number characters with Arabic numerals
		for (int i = 0; i < chineseDigits.length; i++) {
			s = s.replace(chineseDigits[i], String.valueOf(arabicDigits[i]));
		}
		return s;
	}

	private static void clickAction(CT_OutlineElem ct_outlineElem, ST_ID id) {
		CT_Action ct_action = new CT_Action();
		ct_action.setEvent(EventType.CLICK);
		Goto aGoto = new Goto().setDest(new CT_Dest()
				.setType(DestType.XYZ)
				.setPageID(new ST_RefID(id))
//                .setLeft(0)
//                .setRight(595)
//                .setTop(0)
//                .setBottom(842)
		);
		ct_action.setAction(aGoto);
		Actions actions1 = new Actions();
		actions1.addAction(ct_action);
		ct_outlineElem.setActions(actions1);
	}

	public static void main3(String[] args) throws IOException, JAXBException {
		String path = "E:\\receiveDa\\web\\gbPath\\45d13c5b-5239-406e-939c-40c89dbf5179";
		String xmlPath = path + File.separator + "王向恒418475199651471542.xml";
		byte[] bytes = Files.readAllBytes(Paths.get(xmlPath));
		String content = new String(bytes, StandardCharsets.UTF_8);
		UserDaRs userDaRs = GbUtils.xmlUnSerials(content);
		createOfdByIms(path, userDaRs);
	}

	public static Boolean createMenu4(String ofdPathStr, List<CatalogItem> menus) {
		Path ofdPath = Paths.get(ofdPathStr);
		try (OFDReader reader = new OFDReader(ofdPath);
			 OFDDoc ofdDoc1 = new OFDDoc(reader, ofdPath)) {

			Pages pages = ofdDoc1.getOfdDocument().getPages();
			List<org.ofdrw.core.basicStructure.pageTree.Page> pages1 = pages.getPages();
			List<ST_ID> collect = pages1.stream().map(p -> p.getID()).collect(Collectors.toList());
			//添加大纲
			addOut(ofdDoc1, collect, menus);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		return false;
	}

	public static void main(String[] args) {
		String path = "E:\\receiveDa\\web\\gbPath\\45d13c5b-5239-406e-939c-40c89dbf5179\\王向恒418475199651471542.ofd";
		List<CatalogItem> menus = Lists.newArrayList();
		CatalogItem catalogItem = new CatalogItem();
		catalogItem.setClassNo("一");
		catalogItem.setRsdaml002("履历材料");
		catalogItem.setRsdaml004("履历材料");
		catalogItem.setRsdaml005(3);
		catalogItem.setId("1526838701379174402");
		catalogItem.setParentId("1526838701316259845");
		catalogItem.setA0000("45d13c5b-5239-406e-939c-40c89dbf5179");

		CatalogItem catalogItem2 = new CatalogItem();
		List<CatalogItem> children = Lists.newArrayList();
		catalogItem.setChildren(children);
		children.add(catalogItem2);
		catalogItem2.setClassNo("一");
		catalogItem2.setParent(catalogItem);
		catalogItem2.setRsdaml000("9509c9f1-858d-4124-9a0c-f1e1d0520e2b");
		catalogItem2.setRsdaml002("一");
		catalogItem2.setChildren(Lists.newArrayList());
		catalogItem2.setRsdaml004("1994干部履历表");
		catalogItem2.setRsdaml005(3);
		catalogItem2.setId("1526838701379174402");
		catalogItem2.setParentId("1526838701316259845");
		catalogItem2.setA0000("45d13c5b-5239-406e-939c-40c89dbf5179");
		menus.add(catalogItem);
		createMenu4(path, menus);
	}

}
